package controllers

import (
	"baokaobang/datasourse"
	"baokaobang/models"
	"baokaobang/utils"
	"bytes"
	"encoding/json"
	"fmt"
	"github.com/go-xorm/xorm"
	"github.com/kataras/iris/v12"
	"io"
	"os"
	"strings"
)

type YxsController struct {
	Ctx iris.Context
}

func IsLetter(s string) bool {
	for _, r := range s {
		if (r < 'a' || r > 'z') && (r < 'A' || r > 'Z') {
			return false
		}
	}
	return true
}

/*func (c *YxsController) GetTest() interface{} {
	msg := c.Ctx.URLParam("msg")
	msgSec := wechat.NewMsgSec(msg)
	msgSecRes, err := msgSec.Check()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("%s", err.Error()), "")
	}
	if !msgSecRes {
		return utils.CommonRes(1000, "包含违规内容", "")
	}
	return utils.CommonRes(20000, "操作成功", "")
}*/

// 给院校生成注册码
func (c *YxsController) GetGencollegeregcode() interface{} {
	p := utils.Atoi(c.Ctx.URLParam("p"))
	size := 500
	start := (p - 1) * size

	db, err := datasourse.NewMasterOrm()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法连接数据库：%s", err.Error()), "")
	}

	sess := db.NewSession()
	defer sess.Close()
	err = sess.Begin()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("数据库事务开启失败：%s", err.Error()), "")
	}

	collegeList := make([]models.College, 0)
	err = sess.Table(new(models.College)).Limit(size, start).Find(&collegeList)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法连接数据库：%s", err.Error()), "")
	}

	for _, college := range collegeList {
		updateData := map[string]interface{}{}
		code := utils.GenRandCode(4)
		ok, _ := sess.Table(new(models.College)).Where("`reg_code` = ?", code).Exist()
		for ok {
			code = utils.GenRandCode(4)
			ok, _ = sess.Table(new(models.College)).Where("`reg_code` = ?", code).Exist()
		}
		updateData["reg_code"] = code
		_, err = sess.Table(new(models.College)).ID(college.Id).Update(updateData)
		if err != nil {
			return utils.CommonRes(1000, fmt.Sprintf("无法连接数据库：%s", err.Error()), "")
		}
	}

	sess.Commit()

	return utils.CommonRes(20000, "操作成功", "")
}

// 对应major_category表
func (c *YxsController) GetMajorfirst() interface{} {
	db, err := datasourse.NewMasterOrm()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法连接数据库：%s", err.Error()), "")
	}

	sqlStr := "select * from t_d_mainmajorcategory"
	list, err := db.QueryString(sqlStr)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("查询出错：%s", err.Error()), "")
	}

	typeMap := map[string]int{
		"本科": 1,
		"专科": 2,
	}

	for i, _ := range list {
		majorCategory := new(models.MajorCategory)
		majorCategory.Name = list[i]["Name"]
		majorCategory.CategoryType = typeMap[list[i]["Note"]]
		db.InsertOne(majorCategory)
	}

	return utils.CommonRes(20000, "操作成功", "")
}

// 对应major_category表
func (c *YxsController) GetMajorsecond() interface{} {
	db, err := datasourse.NewMasterOrm()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法连接数据库：%s", err.Error()), "")
	}

	sqlStr := "select * from t_d_majorcategory"
	list, err := db.QueryString(sqlStr)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("查询出错：%s", err.Error()), "")
	}

	for i, _ := range list {
		majorCategory := new(models.MajorCategory)
		majorCategory.ParentId = utils.Atoi64(list[i]["MainCategory_id"])
		majorCategory.Name = list[i]["Name"]
		db.InsertOne(majorCategory)
	}

	return utils.CommonRes(20000, "操作成功", "")
}

// 对应major表
func (c *YxsController) GetMajor() interface{} {
	db, err := datasourse.NewMasterOrm()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法连接数据库：%s", err.Error()), "")
	}

	sqlStr := "select * from t_d_major"
	list, err := db.QueryString(sqlStr)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("查询出错：%s", err.Error()), "")
	}

	for i, _ := range list {
		majorCategorySql := fmt.Sprintf("select * from t_d_majorcategory where id = %s", list[i]["Category_id"])
		majorCategory1, _ := db.QueryString(majorCategorySql)

		majorCategory2 := new(models.MajorCategory)
		db.Where("`name` = ?", majorCategory1[0]["Name"]).Get(majorCategory2)

		major := new(models.Major)
		major.Name = list[i]["Name"]
		major.CategoryId = majorCategory2.Id
		major.Desc = list[i]["Guide"]
		db.InsertOne(major)
	}

	return utils.CommonRes(20000, "操作成功", "")
}

// 对应college_enrollment表（用来给考生匹配院校）
func (c *YxsController) GetCollegeenrollment() interface{} {
	p := utils.Atoi(c.Ctx.URLParam("p"))
	size := 500
	start := (p - 1) * size
	sqlStr := fmt.Sprintf("select * from t_gk_university_history_score limit %d,%d", start, size)

	db, err := datasourse.NewMasterOrm()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法连接数据库：%s", err.Error()), "")
	}

	list, err := db.QueryString(sqlStr)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("查询出错：%s", err.Error()), "")
	}

	if len(list) <= 0 {
		return utils.CommonRes(1000, "数据已处理完", "")
	}

	batchMap := map[string]int{
		"本科一批":  1,
		"本科二批":  2,
		"高职高专批": 3,
	}

	subjectMap := map[string]int{
		"文史类": 1,
		"理工类": 2,
	}

	for i, _ := range list {
		college := new(models.College)
		ok, _ := db.Where("`code` = ?", list[i]["ucode"]).Get(college)
		if !ok {
			continue
		}

		collegeEnrollment := new(models.CollegeEnrollment)
		collegeEnrollment.CollegeId = college.Id
		collegeEnrollment.Year = utils.Atoi(list[i]["uyear"])
		collegeEnrollment.Batch = batchMap[list[i]["bachname"]]
		collegeEnrollment.Subject = subjectMap[list[i]["typename"]]
		collegeEnrollment.MinScore = utils.Atoi(list[i]["minscore"])
		collegeEnrollment.MinScoreRank = utils.Atoi(list[i]["minranking"])
		db.InsertOne(collegeEnrollment)
	}

	return utils.CommonRes(20000, "操作成功", "")
}

type EnrollmentDatas struct {
	BatchName  string          `json:"batchName"`
	DataList   [][]interface{} `json:"dataList"`
	EnrollCode string          `json:"enrollCode"`
	EnrollName string          `json:"enrollName"`
}

type EnrollmentData struct {
	AreaId   string            `json:"areaId"`
	AreaName string            `json:"areaName"`
	Datas    []EnrollmentDatas `json:"datas"`
	Titles   []interface{}     `json:"titles"`
}

type EnrollmentDataRes struct {
	Code    int            `json:"code"`
	Data    EnrollmentData `json:"data"`
	Message string         `json:"message"`
}

// 对应enrollment表（录取数据展示）
func (c *YxsController) GetEnrollmentdata() interface{} {
	p := utils.Atoi(c.Ctx.URLParam("p"))
	size := 500
	start := (p - 1) * size
	sqlStr := fmt.Sprintf("select * from university limit %d,%d", start, size)

	db, err := datasourse.NewMasterOrm()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法连接数据库：%s", err.Error()), "")
	}

	list, err := db.QueryString(sqlStr)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("查询出错：%s", err.Error()), "")
	}

	if len(list) <= 0 {
		return utils.CommonRes(1000, "数据已处理完", "")
	}

	ids := make(chan string, 100)

	for i := 1; i <= 8; i++ {
		go GetUniversityEnrollmentData(db, ids)
	}

	for i, _ := range list {
		ids <- list[i]["id"]
	}
	close(ids)

	return utils.CommonRes(20000, "操作成功", "")
}

func GetUniversityEnrollmentData(db *xorm.Engine, ids <-chan string) {
	for id := range ids {
		university := new(models.University)
		ok, _ := db.ID(id).Get(university)
		if !ok {
			continue
		}

		infoUrl := fmt.Sprintf("https://wx.yunxiaosheng.com/yxs/college/getCollegeEnrollScoreLine?collegeId=%s", university.Code)
		content, err := utils.GetRequest(infoUrl)
		if err != nil {
			fmt.Println(err)
			continue
		}

		resData := EnrollmentDataRes{}
		err = json.Unmarshal(content, &resData)
		if err != nil {
			fmt.Println(err)
			continue
		}

		if len(resData.Data.Datas) <= 0 {
			continue
		}

		if len(resData.Data.Titles) <= 0 {
			continue
		}

		for _, item := range resData.Data.Datas {
			dataList := item.DataList
			if len(dataList) <= 0 {
				continue
			}
			if len(dataList[len(dataList)-1]) != 4 {
				continue
			}
			college := new(models.College)
			ok, _ = db.Where("`code` = ?", item.EnrollCode).Get(college)
			if !ok {
				continue
			}

			for i, year := range resData.Data.Titles {
				if i == 0 {
					continue
				}
				enrollment := new(models.Enrollment)
				enrollment.UniversityId = university.Id
				enrollment.CollegeId = college.Id
				enrollment.BatchSubject = item.BatchName
				enrollment.Year = fmt.Sprintf("%.0f", year)
				if dataList[0][i] == "-" {
					enrollment.PlanNum = fmt.Sprintf("%s", dataList[0][i])
				} else {
					enrollment.PlanNum = fmt.Sprintf("%.0f", dataList[0][i])
				}
				if dataList[1][i] == "-" {
					enrollment.ActualNum = fmt.Sprintf("%s", dataList[1][i])
				} else {
					enrollment.ActualNum = fmt.Sprintf("%.0f", dataList[1][i])
				}
				if dataList[2][i] == "-" {
					enrollment.HighScore = fmt.Sprintf("%s", dataList[2][i])
				} else {
					enrollment.HighScore = fmt.Sprintf("%.0f", dataList[2][i])
				}
				if dataList[3][i] == "-" {
					enrollment.HighScoreRank = fmt.Sprintf("%s", dataList[3][i])
				} else {
					enrollment.HighScoreRank = fmt.Sprintf("%.0f", dataList[3][i])
				}
				if dataList[4][i] == "-" {
					enrollment.LowScore = fmt.Sprintf("%s", dataList[4][i])
				} else {
					enrollment.LowScore = fmt.Sprintf("%.0f", dataList[4][i])
				}
				if dataList[5][i] == "-" {
					enrollment.LowScoreRank = fmt.Sprintf("%s", dataList[5][i])
				} else {
					enrollment.LowScoreRank = fmt.Sprintf("%.0f", dataList[5][i])
				}
				if dataList[6][i] == "-" {
					enrollment.BatchLine = fmt.Sprintf("%s", dataList[6][i])
				} else {
					enrollment.BatchLine = fmt.Sprintf("%.0f", dataList[6][i])
				}
				_, err = db.InsertOne(enrollment)
				if err != nil {
					fmt.Println(err)
					continue
				}
			}
		}
	}
}

// 对应enrollment_plan表
func (c *YxsController) GetEnrollmentplan() interface{} {
	p := utils.Atoi(c.Ctx.URLParam("p"))
	size := 500
	start := (p - 1) * size
	sqlStr := fmt.Sprintf("select * from t_gk_plan_major_temp where myear = 2020 limit %d,%d", start, size)

	db, err := datasourse.NewMasterOrm()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法连接数据库：%s", err.Error()), "")
	}

	sess := db.NewSession()
	defer sess.Close()
	err = sess.Begin()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("数据库事务开启失败：%s", err.Error()), "")
	}

	list, err := sess.QueryString(sqlStr)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("查询出错：%s", err.Error()), "")
	}

	if len(list) <= 0 {
		return utils.CommonRes(1000, "数据已处理完", "")
	}

	batchMap := map[string]int{
		"本科一批":  1,
		"本科二批":  2,
		"高职高专批": 3,
	}

	for i, _ := range list {
		university := new(models.University)
		ok, _ := sess.Where("`code` = ?", list[i]["uid"]).Get(university)
		if !ok {
			continue
		}

		college := new(models.College)
		ok, _ = sess.Where("`code` = ?", list[i]["ucode"]).Get(college)
		if !ok {
			continue
		}

		enrollmentPlan := new(models.EnrollmentPlan)
		enrollmentPlan.UniversityId = university.Id
		enrollmentPlan.CollegeId = college.Id
		enrollmentPlan.Year = utils.Atoi(list[i]["myear"])
		enrollmentPlan.MajorName = list[i]["majorname"]
		enrollmentPlan.MajorCode = list[i]["majorcode"]
		enrollmentPlan.Batch = batchMap[list[i]["batchname"]]
		enrollmentPlan.MType = utils.Atoi(list[i]["utypecode"])
		enrollmentPlan.StudentNum = utils.Atoi(list[i]["plannumber"])
		enrollmentPlan.Tuition = utils.Atoi(list[i]["charge"])

		_, err = sess.InsertOne(enrollmentPlan)
		if err != nil {
			return utils.CommonRes(1000, fmt.Sprintf("%s %s%s %s插入失败：%s", list[i]["charge"], list[i]["ucode"], list[i]["uname"], list[i]["majorname"], err.Error()), "")
		}
	}

	sess.Commit()

	return utils.CommonRes(20000, "操作成功", "")
}

// 对应admission_data表（用来进行志愿检测，只2018年与2019年，2017年有问题，不用）
func (c *YxsController) GetAdmissiondata() interface{} {
	p := utils.Atoi(c.Ctx.URLParam("p"))
	size := 500
	start := (p - 1) * size
	sqlStr := fmt.Sprintf("select * from t_gk_universty_history_major_score where uyear in (2018,2019) limit %d,%d", start, size)

	db, err := datasourse.NewMasterOrm()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法连接数据库：%s", err.Error()), "")
	}

	sess := db.NewSession()
	defer sess.Close()
	err = sess.Begin()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("数据库事务开启失败：%s", err.Error()), "")
	}

	list, err := sess.QueryString(sqlStr)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("查询出错：%s", err.Error()), "")
	}

	if len(list) <= 0 {
		return utils.CommonRes(1000, "数据已处理完", "")
	}

	batchMap := map[string]int{
		"本科一批":  1,
		"本科二批":  2,
		"高职高专批": 3,
	}

	for i, _ := range list {
		minScore := utils.Atoi(list[i]["minscore"])
		if minScore <= 0 {
			continue
		}

		college := new(models.College)
		ok, _ := sess.Where("`code` = ?", list[i]["ucode"]).Get(college)
		if !ok {
			return utils.CommonRes(1000, fmt.Sprintf("%s%s没有查询到", list[i]["ucode"], list[i]["uname"]), "")
		}

		admissionData := new(models.AdmissionData)
		admissionData.CollegeId = college.Id
		admissionData.Year = utils.Atoi(list[i]["uyear"])
		admissionData.MajorName = list[i]["majorname"]
		admissionData.MajorCode = list[i]["majorcode"]
		admissionData.Batch = batchMap[list[i]["bachname"]]
		admissionData.Subject = utils.Atoi(list[i]["typecode"])
		admissionData.MinScore = minScore

		minRank := new(models.Rank)
		ok, _ = sess.Where("year = ? and subject = ? and score = ?", list[i]["uyear"], list[i]["typecode"], minScore).Get(minRank)
		if !ok {
			return utils.CommonRes(1000, fmt.Sprintf("%d分 %s", minScore, list[i]["majorname"]), "")
		}
		minRankArr := strings.Split(minRank.Section, "~")
		admissionData.MinScoreHigh = utils.Atoi(minRankArr[0])
		admissionData.MinScoreLow = utils.Atoi(minRankArr[1])

		sess.InsertOne(admissionData)
	}

	sess.Commit()

	return utils.CommonRes(20000, "操作成功", "")
}

// 对应university表
func (c *YxsController) GetUniversitylist() interface{} {
	sqlStr := "select * from t_gk_university"

	db, err := datasourse.NewMasterOrm()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法连接数据库：%s", err.Error()), "")
	}

	list, err := db.QueryString(sqlStr)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("查询出错：%s", err.Error()), "")
	}

	educationLevel := map[string]int{
		"本科":        1,
		"本科/高职(专科)": 1,
		"高职(专科)":    2,
	}

	for i, _ := range list {
		university := new(models.University)
		ok, _ := db.Where("`code` = ?", list[i]["ucode"]).Get(university)
		if !ok {
			newUniversity := new(models.University)
			newUniversity.Name = list[i]["uname"]
			newUniversity.Code = list[i]["ucode"]
			newUniversity.LogoPic = list[i]["logo"]
			newUniversity.MType = educationLevel[list[i]["educationLevel"]]
			newUniversity.Introduction = list[i]["introduction"]
			newUniversity.Address = list[i]["address"]
			newUniversity.Website = list[i]["website"]
			newUniversity.Telephone = list[i]["contacttel"]
			db.InsertOne(newUniversity)
		}
	}

	return utils.CommonRes(20000, "操作成功", "")
}

// 对应college表
func (c *YxsController) GetCollegelist() interface{} {
	sqlStr := "select any_value(uid) as uid,any_value(uname) as uname,any_value(ucode) as ucode from t_gk_universty_history_major_score where uyear in (2018,2019) group by ucode"

	db, err := datasourse.NewMasterOrm()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法连接数据库：%s", err.Error()), "")
	}

	list, err := db.QueryString(sqlStr)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("查询出错：%s", err.Error()), "")
	}

	for i, _ := range list {
		university := new(models.University)
		db.Where("`code` = ?", list[i]["uid"]).Get(university)
		college := new(models.College)
		college.UniversityId = university.Id
		college.Code = list[i]["ucode"]
		college.Name = list[i]["uname"]
		db.InsertOne(college)
	}

	return utils.CommonRes(20000, "查询成功", "")
}

type UniversityListInfo struct {
	CollegeCode     string     `json:"collegeCode"`
	CollegeFeatures [][]string `json:"collegeFeatures"`
	CollegeId       string     `json:"CollegeId"`
	CollegeName     string     `json:"collegeName"`
	EducationLevel  string     `json:"educationLevel"`
	Recommend       int        `json:"recommend"`
	SchoolBadge     string     `json:"schoolBadge"`
	SchoolBadgeUrl  string     `json:"schoolBadgeUrl"`
}

type UniversityListResData struct {
	DataList   []UniversityListInfo `json:"dataList"`
	TotalCount int                  `json:"totalCount"`
}

type UniversityListRes struct {
	Code    int                   `json:"code"`
	Data    UniversityListResData `json:"data"`
	Message string                `json:"message"`
}

// 获取大学列表（从云校生获取）
/*func (c *YxsController) GetUniversity() interface{} {
	p := c.Ctx.URLParam("p") // 当前页
	infoUrl := fmt.Sprintf("https://wx.yunxiaosheng.com/yxs/college/getCollegeWithPage?pageIndex=%s&pageSize=200", p)
	infoByte, err := utils.GetRequest(infoUrl)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("第%s页请求出错：%s", p, err.Error()), "")
	}
	res := UniversityListRes{}
	err = json.Unmarshal(infoByte, &res)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("第%s页数据解析出错：%s", p, err.Error()), "")
	}
	if len(res.Data.DataList) <= 0 {
		return utils.CommonRes(20000, "所有数据已操作完成", "")
	}

	db, err := datasourse.NewMasterOrm()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法连接数据库：%s", err.Error()), "")
	}

	sess := db.NewSession()
	defer sess.Close()
	err = sess.Begin()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("数据库事务开启失败：%s", err.Error()), "")
	}

	educationLevel := map[string]int{
		"本科":     1,
		"高职(专科)": 2,
	}

	list := res.Data.DataList
	for _, item := range list {
		university := new(models.University)
		university.Name = item.CollegeName
		university.Code = item.CollegeCode
		university.MType = educationLevel[item.EducationLevel]
		_, err = sess.InsertOne(university)
		if err != nil {
			return utils.CommonRes(1000, fmt.Sprintf("%s%s插入失败：%s", item.CollegeCode, item.CollegeName, err.Error()), "")
		}
		if len(item.CollegeFeatures) > 0 {
			for _, feature := range item.CollegeFeatures {
				if len(feature) > 0 {
					for _, label := range feature {
						universityLabel := new(models.UniversityLabel)
						ok, _ := sess.Where("`name` = ?", label).Get(universityLabel)
						if !ok {
							universityLabel.Name = label
							sess.InsertOne(universityLabel)
						}
						universityLabelRelation := new(models.UniversityLabelRelation)
						universityLabelRelation.UniversityId = university.Id
						universityLabelRelation.UniversityLabelId = universityLabel.Id
						sess.InsertOne(universityLabelRelation)
					}
				}
			}
		}
	}
	sess.Commit()

	return utils.CommonRes(20000, "数据插入成功", "")
}*/

// 获取大学详细信息
func (c *YxsController) GetUniversitydetail() interface{} {
	p := utils.Atoi(c.Ctx.URLParam("p")) // 当前页
	size := 200
	start := (p - 1) * size

	db, err := datasourse.NewMasterOrm()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法连接数据库：%s", err.Error()), "")
	}

	ids := make(chan string, 100)

	universityList := make([]models.University, 0)
	err = db.Limit(size, start).Find(&universityList)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("大学列表获取失败：%s", err.Error()), "")
	}

	for i := 1; i <= 8; i++ {
		go GetUniversityInfo(db, ids)
	}

	for _, university := range universityList {
		ids <- university.Code
	}
	close(ids)

	return utils.CommonRes(20000, "操作成功", "")
}

type UniversityInfoData struct {
	Address        string `json:"address"`
	AreaId         string `json:"areaId"`
	Introduction   string `json:"introduction"`
	IsPublic       int    `json:"isPublic"`
	SchoolBadgeUrl string `json:"schoolBadgeUrl"`
	Telephone      string `json:"telephone"`
	Website        string `json:"website"`
}

type UniversityInfo struct {
	Code    int                `json:"code"`
	Data    UniversityInfoData `json:"data"`
	Message string             `json:"message"`
}

func GetUniversityInfo(db *xorm.Engine, ids <-chan string) {
	for id := range ids {
		infoUrl := fmt.Sprintf("https://wx.yunxiaosheng.com/yxs/college/getCollegeInfo?collegeId=%s", id)
		content, err := utils.GetRequest(infoUrl)
		if err != nil {
			return
		}
		universityInfo := UniversityInfo{}
		err = json.Unmarshal(content, &universityInfo)
		if err != nil {
			return
		}

		updateData := map[string]interface{}{
			"nature":       universityInfo.Data.IsPublic,
			"logo_pic":     universityInfo.Data.SchoolBadgeUrl,
			"introduction": universityInfo.Data.Introduction,
			"address":      universityInfo.Data.Address,
			"website":      universityInfo.Data.Website,
			"telephone":    universityInfo.Data.Telephone,
		}

		area := strings.Split(universityInfo.Data.AreaId, " ")
		if len(area) == 1 {
			province := new(models.Region)
			db.Where("`code` = ?", area[0]).Get(province)
			updateData["province_id"] = province.Id
		} else if len(area) == 2 {
			province := new(models.Region)
			db.Where("`code` = ?", area[0]).Get(province)
			updateData["province_id"] = province.Id

			city := new(models.Region)
			db.Where("`code` = ?", area[1]).Get(city)
			updateData["city_id"] = city.Id
		}

		db.Table(new(models.University)).Where("`code` = ?", id).Update(updateData)
	}
}

// 将区域表(region)中code字段修改为6位数
func (c *YxsController) GetIndex() interface{} {
	db, err := datasourse.NewMasterOrm()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法连接数据库：%s", err.Error()), "")
	}

	regionList := make([]models.Region, 0)
	err = db.Find(&regionList)
	if err != nil {
		return utils.CommonRes(1000, "无法获取区域列表", "")
	}

	for _, region := range regionList {
		n := 6 - len(region.Code)
		if n > 0 {
			code := fmt.Sprintf("%s%s", region.Code, strings.Repeat("0", n))
			updateData := map[string]interface{}{
				"code": code,
			}
			db.Table(new(models.Region)).ID(region.Id).Update(updateData)
		}
	}

	return utils.CommonRes(20000, "操作成功", "")
}

func removeDuplicate(majorList []models.Major) []models.Major {
	resultMap := map[string]bool{}
	for _, v := range majorList {
		data, _ := json.Marshal(v)
		resultMap[string(data)] = true
	}
	result := []models.Major{}
	for k := range resultMap {
		var t models.Major
		json.Unmarshal([]byte(k), &t)
		result = append(result, t)
	}
	return result
}

func (c *YxsController) GetLogo() interface{} {
	p := utils.Atoi(c.Ctx.URLParam("p")) // 当前页
	size := 100
	start := (p - 1) * size

	db, err := datasourse.NewMasterOrm()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法连接数据库：%s", err.Error()), "")
	}

	universityList := make([]models.University, 0)
	err = db.Limit(size, start).Find(&universityList)
	if err != nil {
		return utils.CommonRes(1000, "无法查询大学到大学列表", "")
	}

	for _, university := range universityList {
		body, err := utils.GetRequest(university.LogoPic)
		if err != nil {
			continue
		}
		name := fmt.Sprintf("/var/www/statics/uploadfiles/university_logo/%s.jpg", university.Code)
		logo, _ := os.Create(name)
		defer logo.Close()
		io.Copy(logo, bytes.NewReader(body))
		updateData := map[string]interface{}{
			"logo_pic_local": fmt.Sprintf("/uploadfiles/university_logo/%s.jpg", university.Code),
		}
		db.Table(new(models.University)).ID(university.Id).Update(updateData)
	}

	return utils.CommonRes(20000, "操作成功", "")
}

type EnrollProfileData struct {
	CollegeId   string `json:"collegeId"`
	CollegeName string `json:"collegeName"`
	DetailUrl   string `json:"detailUrl"`
	FilePath    string `json:"filePath"`
	ProfileId   string `json:"profileId"`
	Year        string `json:"year"`
}

type EnrollProfileList struct {
	Code    int                 `json:"code"`
	Data    []EnrollProfileData `json:"data"`
	Message string              `json:"message"`
}

func (c *YxsController) GetEnrollprofile() interface{} {
	p := utils.Atoi(c.Ctx.URLParam("p")) // 当前页
	size := 100
	start := (p - 1) * size

	db, err := datasourse.NewMasterOrm()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法连接数据库：%s", err.Error()), "")
	}

	universityList := make([]models.University, 0)
	err = db.Limit(size, start).Find(&universityList)
	if err != nil {
		return utils.CommonRes(1000, "无法查询大学到大学列表", "")
	}

	if len(universityList) <= 0 {
		return utils.CommonRes(20000, "数据已处理完毕", "")
	}

	for _, university := range universityList {
		infoUrl := fmt.Sprintf("https://wx.yunxiaosheng.com/yxs/profile/getEnrollProfileList?collegeId=%s", university.Code)
		infoByte, err := utils.GetRequest(infoUrl)
		if err != nil {
			continue
		}
		enrollProfileList := EnrollProfileList{}
		err = json.Unmarshal(infoByte, &enrollProfileList)
		if err != nil {
			continue
		}
		if len(enrollProfileList.Data) <= 0 {
			continue
		}
		for _, enrollProfile := range enrollProfileList.Data {
			detailUrl := fmt.Sprintf("https://wx.yunxiaosheng.com/gkzszc/%s/%s.html", enrollProfile.Year, university.Code)
			detailByte, err := utils.GetRequest(detailUrl)
			if err != nil {
				continue
			}
			enrollProfileModel := new(models.EnrollProfile)
			enrollProfileModel.Year = utils.Atoi(enrollProfile.Year)
			enrollProfileModel.UniversityId = university.Id
			enrollProfileModel.Content = string(detailByte)
			db.InsertOne(enrollProfileModel)
		}
	}

	return utils.CommonRes(20000, "操作成功", "")
}
